package com.j2ee.struts.action.result;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;

import javax.imageio.ImageIO;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.Result;

/**
 * 生成随机验证码
 * @author LC
 *
 */
@SuppressWarnings("serial")
public class CodeImageResult implements Result{
	
	private int width = 120 ;
	private int height = 25 ;

	public void setWidth(int width) {
		this.width = width;
	}

	public void setHeight(int height) {
		this.height = height;
	}

	public void execute(ActionInvocation actioninvocation) throws Exception {
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB) ;
		Graphics graphics = image.getGraphics();
		graphics.setColor(Color.BLUE) ;
		graphics.drawRect(0, 0, width, height);
		graphics.setColor(Color.YELLOW) ;
		graphics.fillRect(1, 1, width-2, height-2);
		graphics.setColor(Color.GRAY) ;
		Random random = new Random() ;
		for(int i=0; i<10; i++) {
			graphics.drawLine(random.nextInt(width), random.nextInt(height), random.nextInt(width), random.nextInt(height)) ;
		}
		graphics.setColor(Color.RED) ;
		graphics.setFont(new Font("宋体", Font.BOLD|Font.ITALIC, 18)) ;
		int x = 25 ;
		for (int i = 0; i < 4; i++) {
			graphics.drawString(random.nextInt(10)+"", x, 20) ;
			x+=18 ;
		}
		ImageIO.write(image, "jpg", ServletActionContext.getResponse().getOutputStream()) ;
	}

}
